package org.goyo.main.services.system.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.exception.DBException;
import org.goyo.common.exception.ServiceException;
import org.goyo.common.utils.Pager;
import org.goyo.main.domain.dao.system.ISysDepGroupDao;
import org.goyo.main.domain.entity.system.SysDepGroup;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.services.system.ISysDepGroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SysDepGroupServiceImpl implements ISysDepGroupService {
  protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private ISysDepGroupDao sysDepGroupDao;
	
	@Override
	public List<SysDepGroup> getAllSysDepGroup() throws DBException,
			ServiceException{
		List<SysDepGroup> list = sysDepGroupDao.findByCond(null, null);
		return list;
	}

	@Override
	public String saveOrUpdateInfo(SysDepGroup info) throws DBException,ServiceException {
	  String pid = info.getParentId();
  	  if(!StringUtils.isEmpty(pid)){
  	    sysDepGroupDao.updateByHql("update SysDepGroup set leaf=? where id=? ", new Object[]{false,pid});
      }
		String uuid = null;
		if(info.getUuid() == null || "".equals(info.getUuid())){
			info.setUuid(null);
			uuid = sysDepGroupDao.save(info);
		}else{
		  uuid = info.getUuid();
		  if(sysDepGroupDao.countByHql("select count(*) from SysDepGroup where parentId ='"+uuid+"'")>0){
		    info.setLeaf(false);
		  }else{
		    info.setLeaf(true);
		  }
			sysDepGroupDao.update(info);
		}
		return uuid;
	}

	@Override
	public void delByUuids(String[] uuids) throws DBException, ServiceException {
		sysDepGroupDao.delBatch(SysDepGroup.class, "uuid", uuids);
	}

  @Override
  public Pager<SysUser> findByCondition(String where, Pager pager) throws DBException,
      ServiceException {
    return  sysDepGroupDao.findByCondition(where, pager);
    }

  @Override
  public String getDepGroupSerialNumber() throws DBException, ServiceException {
    int i =0;
    try {
      List list =  sysDepGroupDao.findObjects("select max(CAST(number AS  int)) from SysDepGroup", null, null);
      if(null!=list){
       i =(Integer)list.get(0)+1;
      }
    } catch (Exception e) {
      i=0;
      logger.error(e.getMessage(),e);
    }
    String pattern="0000";
    java.text.DecimalFormat df = new java.text.DecimalFormat(pattern);
    return df.format(i)+"";
  }

}
